import { Elysia } from 'elysia';

import { config } from '@/config';
import { getServiceUrl } from '@/config/utils';
import { accessLoggerMiddleware } from '@/middleware/access-logger';
import { responseWrapperMiddleware } from '@/middleware/response-wrapper';
import {
  createCorsConfig,
  createStaticConfig,
  createSwaggerConfig,
} from '@/plugins';
import { apiRoutes } from '@/routes/api';
import { logger } from '@/utils/logger';

export const app = new Elysia({
  name: config.app.name,
})
  .use(createCorsConfig())
  .use(createSwaggerConfig())
  .use(createStaticConfig())
  .use(accessLoggerMiddleware)
  .use(responseWrapperMiddleware)
  .use(apiRoutes);

// 如果直接运行此文件则启动服务器
if (import.meta.main) {
  // 设置优雅关闭
  const shutdown = async () => {
    logger.info('🛑 正在关闭服务器...');
    process.exit(0);
  };
  process.on('SIGINT', shutdown);
  process.on('SIGTERM', shutdown);

  app.listen(config.server.port);

  // 获取正确的访问信息
  const { external } = getServiceUrl();
  // 显示主要服务信息
  logger.info(`🚀 服务器运行在 ${external}`);
  logger.info(`📋 API文档地址: ${external}${config.swagger.path}`);
}
